import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { UserInfoDTO } from "@/types/user";
import { authApi } from "@/api/user";
import type { ApiResponse } from "@/types/api";
import { CacheKeyEnum } from "@/constants/cacheKey";
import useCache from "@/hooks/useCache";

const cache = useCache();

export const getUserInfoAsync = createAsyncThunk("userSlice/getUserInfoAsync", async (_, thunkAPI) => {
  try {
    return await authApi.getUserInfo();
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});

interface UserState {
  userInfo: UserInfoDTO | null;
  isLoading: boolean;
  error: string | null;
}

const userSlice = createSlice({
  name: "userSlice",
  initialState: {
    userInfo: cache.get(CacheKeyEnum.USER) || null,
    isLoading: false,
    error: null,
  } as UserState,
  reducers: {
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    setLoading(state, action) {
      state.isLoading = action.payload;
    },
    setError(state, action) {
      state.error = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getUserInfoAsync.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(getUserInfoAsync.fulfilled, (state, action) => {
        state.isLoading = false;
        state.userInfo = action.payload;
        cache.set(CacheKeyEnum.USER, action.payload);
        console.log("存储用户信息到缓存111:", cache.get(CacheKeyEnum.USER));
        
      })
      .addCase(getUserInfoAsync.rejected, (state, action) => {
        state.isLoading = false;
        state.error = (action.payload as ApiResponse).message || "获取用户信息失败";
        cache.remove(CacheKeyEnum.USER);
      });
  },
});

export const { setUserInfo, setLoading, setError } = userSlice.actions;
export default userSlice.reducer;
